package com.spring.servlet;

import com.spring.context.ApplicationContext;
import com.spring.pojo.ApiResult;
import com.spring.service.TransferService;
import com.spring.utils.JsonUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author SpringWang
 * @date 2021/5/19
 */
@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    private TransferService transferService;
    private ApplicationContext applicationContext;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        int money = Integer.parseInt(req.getParameter("money"));

        ApiResult apiResult = new ApiResult();

        try {
            transferService.transfer(fromCardNo, toCardNo, money);
        } catch (Exception e) {
            e.printStackTrace();
            apiResult.setSuccess(false);
            apiResult.setMessage(e.toString());
        }

        //response
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(apiResult));
    }
}
